package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.FloorHomeRecyclerViewAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseActivity;
import com.weixin.paleituo.bean.CityListBean;
import com.weixin.paleituo.bean.HouseListBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.CheckCityEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.AlertPopuCommon;
import com.weixin.paleituo.view.LoadingPager;
import com.weixin.paleituo.view.YRecycleview;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class FloorHomeActivity extends BaseActivity {

    @BindView(R.id.iv_back_activity_floorhome)
    ImageView mIvBackActivityFloorhome;
    @BindView(R.id.iv_dw_activity_floor_home)
    ImageView mIvDwActivityFloorHome;
    @BindView(R.id.rwcyclerview_activity_floor_home)
    YRecycleview mRwcyclerviewActivityFloorHome;
    @BindView(R.id.ll_city_activity_floor_home)
    LinearLayout mllCityRoot;
    @BindView(R.id.tv_city_activity_floor_home)
    TextView mTvCity;
    @BindView(R.id.rl_headroot_activity_floor_home)
    RelativeLayout mRlheadRoot;
    @BindView(R.id.viewline_activity_floor_home)
    View mViewline;
    private FloorHomeRecyclerViewAdapter mAdapter;
    private List<HouseListBean> mDataBeans;
    private int currentPage=1;
    private LinkedList<String> mStringList;


    private CompositeDisposable mCompositeDisposable;
    private LoadingPager mLoadingPager;

    private String selectCity="全部";
    private String mCityId="";
    private Map<String, String> mMap;
    private Dialog mLoadingDialog;
    private AlertPopuCommon mPopuCommon;


    public static void startActivity(Context context) {
        Intent intent = new Intent(context, FloorHomeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        //R.layout.activity_floor_home
        mLoadingPager = new LoadingPager(this) {
            @Override
            protected void close() {
            finish();
            }

            @Override
            protected View createSuccessView() {
                //R.layout.activity_floor_home
                return UIUtils.inflate(FloorHomeActivity.this, R.layout.activity_floor_home);
            }

            @Override
            protected void reLoading() {
                retryLoading();
            }
        };
        setContentView(mLoadingPager);

    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        mCompositeDisposable = new CompositeDisposable();
        mMap = new HashMap<>();



        mStringList = new LinkedList<>();
        mStringList.addFirst("全部");
        mDataBeans = new ArrayList<>();
        mAdapter = new FloorHomeRecyclerViewAdapter(this, mDataBeans);
        //设置布局管理器
        mRwcyclerviewActivityFloorHome.setLayoutManager(new LinearLayoutManager(this));
        //设置adapter
        mRwcyclerviewActivityFloorHome.setAdapter(mAdapter);
        //设置Item增加、移除动画
        mRwcyclerviewActivityFloorHome.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
       /* mRwcyclerviewActivityFloorHome.addItemDecoration(new DividerItemDecoration(
                this, DividerItemDecoration.VERTICAL));*/
        mRwcyclerviewActivityFloorHome.setRefreshAndLoadMoreListener(new YRecycleview.OnRefreshAndLoadMoreListener() {
            @Override
            public void onRefresh() {
                Observable<StatusCode<List<HouseListBean>>> houseList = ApiUtils.getApi().getHouseList(mCityId, Contans.rows, "1");
                HttpUtil.getInstance().toSubscribe(houseList, new ProgressSubscriber<List<HouseListBean>>(FloorHomeActivity.this) {

                    @Override
                    protected void _onNext(StatusCode<List<HouseListBean>> t) {
                        List<HouseListBean> houseListBeans = t.getData();
                        if (houseListBeans!=null && houseListBeans.size()!=0){
                            mDataBeans.clear();
                            mDataBeans.addAll(houseListBeans);
                            ToastUtils.makeText("刷新成功");
                            currentPage=1;
                        }else {
                            ToastUtils.makeText("刷新失败");
                        }
                        mRwcyclerviewActivityFloorHome.setReFreshComplete();
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void _onError(String message) {

                        ToastUtils.makeText(message);
                        mRwcyclerviewActivityFloorHome.setReFreshComplete();
                        mAdapter.notifyDataSetChanged();

                    }
                },"houserlist",lifecycleSubject,false,true);
            }

            @Override
            public void onLoadMore() {
                currentPage++;
                final Observable<StatusCode<List<HouseListBean>>> houseList = ApiUtils.getApi().getHouseList(mCityId,  Contans.rows, currentPage + "");
                HttpUtil.getInstance().toSubscribe(houseList, new ProgressSubscriber<List<HouseListBean>>(FloorHomeActivity.this) {


                    @Override
                    protected void _onNext(StatusCode<List<HouseListBean>> t) {
                        List<HouseListBean> houseListBeans = t.getData();
                        if (houseListBeans!=null && houseListBeans.size()>0){
                            mDataBeans.addAll(houseListBeans);
                            mRwcyclerviewActivityFloorHome.setloadMoreComplete();
                            mAdapter.notifyDataSetChanged();
                        }else {

                            ToastUtils.makeText("已经加载全部数据");
                            currentPage--;
                        }
                        mRwcyclerviewActivityFloorHome.setloadMoreComplete();
                        mAdapter.notifyDataSetChanged();

                    }

                    @Override
                    protected void _onError(String message) {
                        currentPage--;
                     //   LogUtils.i(TAG,"楼盘列表 加载更多 "+e.toString());
                        ToastUtils.makeText(message);
                        mRwcyclerviewActivityFloorHome.setloadMoreComplete();
                        mAdapter.notifyDataSetChanged();
                    }
                },"houselist",lifecycleSubject,false,true);


                //mRwcyclerviewActivityFloorHome.setloadMoreComplete();

            }
        });
     /*   if (mDataBeans.size()==0){
            initHouseListData();
        }*/

        retryLoading();

    }

    /**
     * 重新加载
     */
    private void retryLoading() {

        Observable<StatusCode<List<HouseListBean>>> statusCodeObservable = ApiUtils.getApi().getCity(BaseApplication.getToken())
                .flatMap(new Function<StatusCode<List<CityListBean>>, ObservableSource<StatusCode<List<HouseListBean>>>>() {
            @Override
            public ObservableSource<StatusCode<List<HouseListBean>>> apply(StatusCode<List<CityListBean>> listStatusCode) throws Exception {
                LogUtils.i(TAG,"初始化 ：获取城市列表"+listStatusCode);
                LogUtils.i(TAG,"定位城市 ：："+BaseApplication.sLocationCity);
                if (listStatusCode != null && listStatusCode.isFlag() && listStatusCode.getData() != null) {
                    List<CityListBean> data = listStatusCode.getData();
                    mStringList.clear();
                    mMap.clear();
                    for (CityListBean cityListBean : data) {
                        mStringList.add(cityListBean.getName());
                        mMap.put(cityListBean.getName(),cityListBean.getId()+"");
                    }
                    for (CityListBean cityListBean : data) {
                        if (cityListBean.getName().equals(BaseApplication.sLocationCity)) {
                            //获取城市列表成功
                            selectCity=cityListBean.getName();
                            mCityId=cityListBean.getId()+"";
                            return ApiUtils.getApi().getHouseList(mCityId, Contans.rows, "1");
                        }

                    }
                }
                    return ApiUtils.getApi().getHouseList(mCityId,  Contans.rows, "1");

            }
        });

        //获取城市列表
            initHouseListData(statusCodeObservable);


    }

    /**
     * 初始化列表
     */
    private void initHouseListData(Observable<StatusCode<List<HouseListBean>>> houseList) {
     //   final Observable<StatusCode<List<HouseListBean>>> houseList = ApiUtils.getApi().getHouseList("", rows, "1");
        HttpUtil.getInstance().toSubscribe(houseList, new ProgressSubscriber<List<HouseListBean>>(this) {
            @Override
            protected void _onNext(StatusCode<List<HouseListBean>> t) {
                List<HouseListBean> houseListBeans = t.getData();
                if (houseListBeans!=null && houseListBeans.size()>0){
                    //成功
                    mDataBeans.addAll(houseListBeans);
                    mAdapter.notifyDataSetChanged();
                    mLoadingPager.showPagerView(Contans.STATE_SUCCEED);

                }else {
                    //数据为空
                    mLoadingPager.showPagerView(Contans.STATE_EMPTY);
                }

                mTvCity.setText(selectCity);
            }

            @Override
            protected void _onError(String message) {

                mLoadingPager.showPagerView(Contans.STATE_ERROR);

                ToastUtils.makeText(message);


            }

        }, "houselist", lifecycleSubject, false, true);

    }

    @Override
    protected void initEvent() {
        mAdapter.setOnItemClickListener(new FloorHomeRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onClick(View v, int position) {
                LogUtils.i(TAG, position + "");

                String houseId = mDataBeans.get(position).getId() + "";
                HouseDetailsActivity.startActivity(FloorHomeActivity.this,houseId);

            }
        });

    }

    @OnClick(R.id.iv_back_activity_floorhome)
    public void onMIvBackActivityFloorhomeClicked() {

        MainActivity.goGoodsShop(this,0);
        finish();
    }

    @OnClick(R.id.ll_city_activity_floor_home)
    public void onMllcityActivityFloorHomeClicked(View view) {
if (!mStringList.getFirst().equals("全部")){
    mStringList.addFirst("全部");
}


if (mPopuCommon==null){

        mPopuCommon = new AlertPopuCommon(this, Contans.DIAG_TYPE_CITY, mStringList,mTvCity.getText().toString());
}else {
    mPopuCommon.setChekStr(mTvCity.getText().toString());
}
        mPopuCommon.showAsDropDown(mViewline,0,20);

    }

    /**
     * 选择城市筛选
     * @param checkCityEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getCint(CheckCityEvent checkCityEvent){
        String mcity = checkCityEvent.getMcity();

        if (mcity.equals(mTvCity.getText().toString())){
            return;
        }
        mTvCity.setText(mcity);

        mCityId = mMap.get(mcity)==null? "" :mMap.get(mcity);

        Observable<StatusCode<List<HouseListBean>>> statusCodeObservable = ApiUtils.getApi().getHouseList(mCityId,  Contans.rows, "1")
                .subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                if (mLoadingDialog == null) {

                    mLoadingDialog = LoadingDialogUtils.createLoadingDialog(FloorHomeActivity.this, "");
                }
                mLoadingDialog.show();

            }
        }).subscribeOn(AndroidSchedulers.mainThread());

        HttpUtil.getInstance().toSubscribe(statusCodeObservable, new ProgressSubscriber<List<HouseListBean>>(FloorHomeActivity.this) {



            @Override
            protected void _onNext(StatusCode<List<HouseListBean>> t) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                List<HouseListBean> houseListBeans = t.getData();
                if (houseListBeans!=null && houseListBeans.size()>0){
                    mDataBeans.clear();
                    mDataBeans.addAll(houseListBeans);
                    mAdapter.notifyDataSetChanged();
                }else {
                    mDataBeans.clear();
                    mAdapter.notifyDataSetChanged();
                }



            }

            @Override
            protected void _onError(String message) {
                ToastUtils.makeText(message);
                mDataBeans.clear();
                mAdapter.notifyDataSetChanged();
                LoadingDialogUtils.closeDialog(mLoadingDialog);

            }
        },"houselist",lifecycleSubject,false,true);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCompositeDisposable.clear();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressed() {
        MainActivity.goGoodsShop(this,0);
        finish();

    }
}
